<?php
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

// Load products from JSON file
$products_json_path = __DIR__ . '/../data/products.json';
$all_products = [];

if (file_exists($products_json_path)) {
    $json_content = file_get_contents($products_json_path);
    $all_products = json_decode($json_content, true) ?? [];
}

// Get search term and category filter
$search = isset($_GET['search']) ? sanitizeInput($_GET['search']) : '';
$category_filter = isset($_GET['category']) ? sanitizeInput($_GET['category']) : '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 12;
$offset = ($page - 1) * $limit;

// Filter products
$filtered_products = $all_products;

if (!empty($search)) {
    $filtered_products = array_filter($filtered_products, function($product) use ($search) {
        return stripos($product['name'], $search) !== false || 
               stripos($product['description'], $search) !== false ||
               stripos($product['category'], $search) !== false;
    });
}

if (!empty($category_filter)) {
    $filtered_products = array_filter($filtered_products, function($product) use ($category_filter) {
        return strtolower($product['category']) === strtolower($category_filter);
    });
}

// Reset array keys
$filtered_products = array_values($filtered_products);

// Get unique categories for filter dropdown
$categories = array_unique(array_column($all_products, 'category'));
sort($categories);

// Group products by category
$products_by_category = [];
foreach ($filtered_products as $product) {
    $cat = $product['category'];
    if (!isset($products_by_category[$cat])) {
        $products_by_category[$cat] = [];
    }
    $products_by_category[$cat][] = $product;
}

// Calculate pagination
$total_products = count($filtered_products);
$total_pages = ceil($total_products / $limit);

// Paginate results (this is a simplified pagination - showing all for now)
$page_title = "Products";
?>
<?php include '../includes/header.php'; ?>

<style>
.product-card-enhanced {
    background: white;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    transition: transform 0.3s, box-shadow 0.3s;
    display: flex;
    flex-direction: column;
}

.product-card-enhanced:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 16px rgba(0,0,0,0.15);
}

.product-image-container {
    position: relative;
    width: 100%;
    height: 250px;
    overflow: hidden;
    background: #f8f9fa;
}

.product-image-container img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.discount-badge {
    position: absolute;
    top: 10px;
    right: 10px;
    background: #e74c3c;
    color: white;
    padding: 5px 10px;
    border-radius: 5px;
    font-size: 0.85rem;
    font-weight: bold;
}

.product-card-body {
    padding: 1.5rem;
    flex: 1;
    display: flex;
    flex-direction: column;
}

.product-category-badge {
    display: inline-block;
    background: #ecf0f1;
    color: #2c3e50;
    padding: 0.25rem 0.75rem;
    border-radius: 15px;
    font-size: 0.85rem;
    margin-bottom: 0.5rem;
}

.product-name {
    font-size: 1.25rem;
    font-weight: bold;
    color: #2c3e50;
    margin-bottom: 0.5rem;
}

.product-price-section {
    margin: 1rem 0;
}

.product-price {
    font-size: 1.5rem;
    font-weight: bold;
    color: #e74c3c;
}

.product-price-original {
    font-size: 1rem;
    color: #7f8c8d;
    text-decoration: line-through;
    margin-left: 0.5rem;
}

.product-description {
    color: #555;
    font-size: 0.9rem;
    line-height: 1.5;
    margin-bottom: 1rem;
    flex: 1;
}

.product-details {
    border-top: 1px solid #ecf0f1;
    padding-top: 1rem;
    margin-top: 1rem;
    font-size: 0.85rem;
}

.product-detail-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 0.5rem;
    color: #555;
}

.product-detail-label {
    font-weight: 600;
    color: #7f8c8d;
}

.category-section {
    margin-bottom: 4rem;
}

.category-header {
    font-size: 2rem;
    color: #2c3e50;
    margin-bottom: 2rem;
    padding-bottom: 1rem;
    border-bottom: 3px solid #e74c3c;
}

@media (max-width: 768px) {
    .products-grid {
        grid-template-columns: 1fr;
    }
    
    .product-image-container {
        height: 200px;
    }
}
</style>

<main style="padding: 2rem 0;">
    <div class="container">
        <!-- Page Header -->
        <div style="text-align: center; margin-bottom: 3rem;">
            <h1>Our Product Collection</h1>
            <p style="color: #7f8c8d; margin-top: 1rem;">Discover our curated selection of premium snacks and sauces</p>
        </div>

        <!-- Filters -->
        <div class="card" style="margin-bottom: 2rem;">
            <form method="GET" action="">
                <div style="display: grid; grid-template-columns: 1fr auto auto; gap: 1rem; align-items: end;">
                    <div class="form-group" style="margin-bottom: 0;">
                        <label for="search">Search Products</label>
                        <input type="text" id="search" name="search" placeholder="Search by name or description..." value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                    
                    <div class="form-group" style="margin-bottom: 0;">
                        <label for="category">Category</label>
                        <select id="category" name="category">
                            <option value="">All Categories</option>
                            <?php foreach ($categories as $cat): ?>
                                <option value="<?php echo htmlspecialchars($cat); ?>" <?php echo $category_filter === $cat ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($cat); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">Filter</button>
                </div>
            </form>
        </div>

        <!-- Results Info -->
        <div style="margin-bottom: 2rem; color: #7f8c8d;">
            <?php if (!empty($search)): ?>
                <p>Search results for "<strong><?php echo htmlspecialchars($search); ?></strong>" - <?php echo count($filtered_products); ?> products found</p>
            <?php elseif (!empty($category_filter)): ?>
                <p>Category: <strong><?php echo htmlspecialchars($category_filter); ?></strong> - <?php echo count($filtered_products); ?> products found</p>
            <?php else: ?>
                <p>Showing <?php echo count($filtered_products); ?> products</p>
            <?php endif; ?>
        </div>

        <!-- Products by Category -->
        <?php if (empty($filtered_products)): ?>
            <div class="card" style="text-align: center; padding: 3rem;">
                <i class="fas fa-search" style="font-size: 3rem; color: #7f8c8d; margin-bottom: 1rem;"></i>
                <h3>No products found</h3>
                <p style="color: #7f8c8d; margin: 1rem 0;">Try adjusting your search criteria or browse all products.</p>
                <a href="index.php" class="btn btn-primary">View All Products</a>
            </div>
        <?php else: ?>
            <?php foreach ($products_by_category as $category => $category_products): ?>
                <div class="category-section">
                    <h2 class="category-header"><?php echo htmlspecialchars($category); ?></h2>
                    <div class="products-grid" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 2rem;">
                        <?php foreach ($category_products as $product): ?>
                            <div class="product-card-enhanced">
                                <div class="product-image-container">
                                    <?php
                                        $imgSrc = $product['image_url'] ?? '';
                                        if ($imgSrc && strpos($imgSrc, 'http') !== 0 && strpos($imgSrc, '/') !== 0) {
                                            $imgSrc = '../assets/images/' . rawurlencode(basename($imgSrc));
                                        }
                                    ?>
                                    <img src="<?php echo htmlspecialchars($imgSrc); ?>" alt="<?php echo htmlspecialchars($product['name']); ?>" loading="lazy">
                                    <?php if ($product['discount_percentage'] > 0): ?>
                                        <div class="discount-badge">-<?php echo $product['discount_percentage']; ?>%</div>
                                    <?php endif; ?>
                                </div>
                                <div class="product-card-body">
                                    <span class="product-category-badge"><?php echo htmlspecialchars($product['category']); ?></span>
                                    <h3 class="product-name"><?php echo htmlspecialchars($product['name']); ?></h3>
                                    <p class="product-description"><?php echo htmlspecialchars(substr($product['description'], 0, 120)) . '...'; ?></p>
                                    
                                    <div class="product-price-section">
                                        <?php if ($product['discount_price']): ?>
                                            <div class="product-price">
                                                $<?php echo number_format($product['discount_price'], 2); ?>
                                                <span class="product-price-original">$<?php echo number_format($product['price'], 2); ?></span>
                                            </div>
                                        <?php else: ?>
                                            <div class="product-price">$<?php echo number_format($product['price'], 2); ?></div>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <div class="product-details">
                                        <div class="product-detail-item">
                                            <span class="product-detail-label">Quantity:</span>
                                            <span><?php echo $product['quantity']; ?></span>
                                        </div>
                                        <div class="product-detail-item">
                                            <span class="product-detail-label">Supplier:</span>
                                            <span><?php echo htmlspecialchars($product['supplier']); ?></span>
                                        </div>
                                        <div class="product-detail-item">
                                            <span class="product-detail-label">Origin:</span>
                                            <span><?php echo htmlspecialchars($product['origin_country']); ?></span>
                                        </div>
                                        <div class="product-detail-item">
                                            <span class="product-detail-label">Spice Level:</span>
                                            <span><?php echo htmlspecialchars($product['spice_level']); ?></span>
                                        </div>
                                        <?php if ($product['discount_percentage'] > 0): ?>
                                            <div class="product-detail-item">
                                                <span class="product-detail-label">Discount:</span>
                                                <span style="color: #e74c3c; font-weight: bold;"><?php echo $product['discount_percentage']; ?>% OFF</span>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <div style="margin-top: 1rem;">
                                        <?php
                                            $imgLink = $product['image_link'] ?? '';
                                            if ($imgLink && strpos($imgLink, 'http') !== 0 && strpos($imgLink, '/') !== 0) {
                                                $imgLink = '../assets/images/' . rawurlencode(basename($imgLink));
                                            }
                                        ?>
                                        <a href="<?php echo htmlspecialchars($imgLink); ?>" target="_blank" class="btn btn-outline" style="width: 100%; margin-bottom: 0.5rem;">
                                            <i class="fas fa-external-link-alt"></i> View Image
                                        </a>
                                        <button class="btn btn-primary add-to-cart" style="width: 100%;" data-product-id="<?php echo $product['id']; ?>" data-product-name="<?php echo htmlspecialchars($product['name']); ?>">
                                            <i class="fas fa-shopping-cart"></i> Add to Cart
                                        </button>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</main>

<?php include '../includes/footer.php'; ?>

<script>
console.log('Products page loaded');

// Add to Cart functionality (if needed for JSON-based products)
function addToCartInline(productId, productName, quantity = 1) {
    console.log('Adding product', productId, productName, 'quantity', quantity);
    
    const button = document.querySelector(`[data-product-id="${productId}"]`);
    if (!button) {
        console.error('Button not found for product', productId);
        return;
    }
    
    const originalText = button.innerHTML;
    button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Adding...';
    button.disabled = true;
    
    // Note: This would need to be connected to your cart API
    // For now, showing an alert
    setTimeout(() => {
        alert('Product "' + productName + '" added to cart! (Note: Cart functionality requires backend integration)');
        button.innerHTML = '<i class="fas fa-check"></i> Added!';
        setTimeout(() => {
            button.innerHTML = originalText;
            button.disabled = false;
        }, 2000);
    }, 500);
}

// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM loaded, initializing add to cart buttons');
    
    const buttons = document.querySelectorAll('.add-to-cart');
    console.log('Found', buttons.length, 'add to cart buttons');
    
    buttons.forEach((button) => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            const productId = this.dataset.productId;
            const productName = this.dataset.productName || 'Product';
            addToCartInline(productId, productName, 1);
        });
    });
});
</script>